<template>
  <span class="typewriter-text">{{ currentText }}<span class="cursor" :class="{ 'cursor-blink': showCursor }">|</span></span>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

interface Props {
  text: string[]
  speed?: number
  delay?: number
  deleteSpeed?: number
}

const props = withDefaults(defineProps<Props>(), {
  speed: 100,
  delay: 2000,
  deleteSpeed: 50
})

const currentText = ref('')
const showCursor = ref(true)
const currentIndex = ref(0)
const isDeleting = ref(false)

let typewriterInterval: number | null = null
let cursorInterval: number | null = null

const typeWriter = () => {
  const currentString = props.text[currentIndex.value]

  if (isDeleting.value) {
    currentText.value = currentString.substring(0, currentText.value.length - 1)
  } else {
    currentText.value = currentString.substring(0, currentText.value.length + 1)
  }

  let typeSpeed = isDeleting.value ? props.deleteSpeed : props.speed

  if (!isDeleting.value && currentText.value === currentString) {
    typeSpeed = props.delay
    isDeleting.value = true
  } else if (isDeleting.value && currentText.value === '') {
    isDeleting.value = false
    currentIndex.value = (currentIndex.value + 1) % props.text.length
    typeSpeed = 500
  }

  typewriterInterval = window.setTimeout(typeWriter, typeSpeed)
}

const toggleCursor = () => {
  showCursor.value = !showCursor.value
}

onMounted(() => {
  typeWriter()
  cursorInterval = window.setInterval(toggleCursor, 500)
})

onUnmounted(() => {
  if (typewriterInterval) {
    clearTimeout(typewriterInterval)
  }
  if (cursorInterval) {
    clearInterval(cursorInterval)
  }
})
</script>

<style scoped>
.typewriter-text {
  position: relative;
}

.cursor {
  color: var(--primary-color, #667eea);
  font-weight: bold;
}

.cursor-blink {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0;
  }
}
</style>